import { createRouter, createWebHistory } from "vue-router";
import store from "@/store";
import { ElMessage } from "element-plus";

const routes = [
    {
        path: "/",
        name: "home",
        component: () => import("../views/HomeView"),
    },
    {
        path: "/user",
        name: "user",
        children: [
            {
                path: "login",
                name: "login",
                component: () => import("../views/user/LoginView"),
            },
            {
                path: "register",
                name: "register",
                component: () => import("../views/user/RegisterView"),
            },
        ],
    },
    {
        path: "/personalInfo",
        name: "personalInfo",
        component: () => import("../views/user/PersonalInfoView"),
    },
    {
        path: "/cart",
        name: "cart",
        component: () => import("../views/cart/CartView"),
    },
    {
        path: "/order",
        name: "order",
        component: () => import("../views/order/OrderView"),
    },
    {
        path: "/address",
        name: "address",
        component: () => import("../views/order/AddressView"),
    },
    {
        path: "/settle",
        name: "settle",
        component: () => import("../views/order/SettleView"),
    },
    {
        path: "/category",
        name: "category",
        component: () => import("../views/category/CategoryView"),
    },
    {
        path: "/detail/:bookID",
        name: "detail",
        component: () => import("../views/detail/DetailView"),
    },
    {
        path: "/:pathMatch(.*)*",
        name: "notFound",
        component: () => import("../views/not-found/NotFoundView"),
    },
];

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes,
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
    if (
        !store.state.isLogin &&
        (to.name === "cart" ||
            to.name === "order" ||
            to.name === "personalInfo" ||
            to.name === "settle" ||
            to.name === "address")
    ) {
        ElMessage({
            type: "error",
            message: "请先登录",
            duration: 3000,
        });
        setTimeout(() => {}, 200);
        next({ name: "login" });
    } else if (store.state.isLogin && (to.name === "login" || to.name === "register")) {
        setTimeout(() => {}, 200);
        next({ name: "home" });
    } else {
        next();
    }
    store.commit("setActiveIndex", to.fullPath);
});

export default router;
